#!/bin/bash
# 健康检查脚本

URL="http://127.0.0.1:8082/health"
TIMEOUT=5
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

response=$(curl -s -w "%{http_code}" -o /dev/null --max-time $TIMEOUT $URL)

if [ $response -eq 200 ]; then
    echo "[$TIMESTAMP] ✓ ERP Mock Server is healthy (HTTP $response)"
    exit 0
else
    echo "[$TIMESTAMP] ✗ ERP Mock Server is down (HTTP $response)"
    echo "[$TIMESTAMP] Attempting to restart service..."

    # 尝试重启服务
    sudo supervisorctl restart erp-mock

    # 等待5秒后再次检查
    sleep 5
    response2=$(curl -s -w "%{http_code}" -o /dev/null --max-time $TIMEOUT $URL)

    if [ $response2 -eq 200 ]; then
        echo "[$TIMESTAMP] ✓ Service restarted successfully"
        exit 0
    else
        echo "[$TIMESTAMP] ✗ Service restart failed, manual intervention required"
        # 这里可以添加告警通知（邮件、企业微信等）
        exit 1
    fi
fi
